package xin.printk.android.view.widget;

import android.content.Context;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.webkit.WebView;

import org.markdownj.MarkdownProcessor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;

public class MarkdownView extends WebView {

    public MarkdownView(Context context) {
        this(context, null);
    }

    public MarkdownView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MarkdownView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void loadMarkdown(String str) {
        loadMarkdown(str, null);
    }

    public void loadMarkdown(String str, String css) {
        loadMarkdownToView(str, css);
    }

    public void loadMarkdownFile(String filename) {
        loadMarkdownFile(filename, null);
    }

    public void loadMarkdownFile(String filename, String css) {
        new LoadMarkdownTask(this, filename, css).execute();
    }

    private static class LoadMarkdownTask extends AsyncTask<String, Integer, String> {

        private WeakReference<MarkdownView> webViewReference;
        private String url;
        private String css;

        LoadMarkdownTask(MarkdownView webView, String url, String css) {
            webViewReference = new WeakReference<>(webView);
            this.url = url;
            this.css = css;
        }

        @Override
        protected String doInBackground(String... params) {
            MarkdownView webView = webViewReference.get();
            if (webView != null) {
                if (url.contains("file:///android_asset/")) {
                    return readFromAssets(webView.getContext(), url.substring("file:///android_asset/".length(), url.length()));
                } else {
                    return readFromAssets(webView.getContext(), url);
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            MarkdownView webView = webViewReference.get();
            if (webView != null) {
                if (result != null) {
                    webView.loadMarkdownToView(result, css);
                } else {
                    webView.loadUrl("about:blank");
                }
            }
        }

        private String readFromAssets(Context context, String filename) {
            try {
                InputStream inputStream = context.getAssets().open(filename);
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder(inputStream.available());
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                    stringBuilder.append(System.getProperty("line.separator"));
                }
                return stringBuilder.toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    private void loadMarkdownToView(String url, String css) {
        MarkdownProcessor processor = new MarkdownProcessor();
        String html = processor.markdown(url);
        if (css != null) {
            html = "<link rel='stylesheet' type='text/css' href=' " + css + "' />" + html;
        }
        loadDataWithBaseURL("markdown://", html, "text/html", "UTF-8", null);
    }
}
